//
//  TT_IMManager.m
//  BaseProject
//
//  Created by 王洋 on 2020/4/28.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "TTStatusBarUtilities.h"
#import "TTMessageView.h"

#import "TT_IMManager.h"

@interface TT_IMManager ()<TIMMessageListener,TIMUserStatusListener>

@end

@implementation TT_IMManager

+ (instancetype)sharedInstance {
    static TT_IMManager * sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [TT_IMManager new];

    });
    return sharedInstance;
}



#pragma mark ----------- businessApi -----------
- (void)BA_IMLogin {
    
    //    [SVProgressHUD showWithStatus:@"正在登录聊天系统"];
        TIMLoginParam * login_param = [[TIMLoginParam alloc ]init];
        login_param.identifier = [TTUserModel sharedObject].identifier;
        login_param.userSig = [TTUserModel sharedObject].userSig;
        login_param.appidAt3rd = [TTUserModel sharedObject].appidAt3rd;
            
    //    WEAKSELF
        [self TTIM_Login:login_param succ:^{

            //登陆成功后监听消息收发
            [[TIMManager sharedInstance] addMessageListener:self];
            //添加登陆状态的监听
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserStatus:) name:TUIKitNotification_TIMUserStatusListener object:nil];

            V2TIMAPNSConfig *confg = [[V2TIMAPNSConfig alloc] init];
            // 企业证书 ID，上传证书到 IM 控制台后生成
            confg.businessID = IM_CERTIFICATE_ID;
            
            // 苹果后台请求的  deviceToken
            confg.token = [TTUserModel sharedObject].deviceToken;
            [[V2TIMManager sharedInstance] setAPNS:confg succ:^{
            } fail:^(int code, NSString *msg) {
            }];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[TT_MessageManager manager] refreshUnReadCount];
            });
            
        } fail:^(int code, NSString *msg) {
            
            NSLog(@"fail %@",msg);

            [SVProgressHUD showWithStatus:msg];
            [SVProgressHUD dismissWithDelay:0.3];
            
        }];
}

- (void)onUserStatus:(NSNotification *)notification
{
    TUIUserStatus status = [notification.object integerValue];
    switch (status) {
        case TUser_Status_ForceOffline: {
            
            [SVProgressHUD showErrorWithStatus:@"您的帐号于另一台手机上登录,本机聊天功能会受到影响,如需使用聊天功能，请退出重新登录"];
            [SVProgressHUD dismissWithDelay:2];
            
        }
            break;
        case TUser_Status_ReConnFailed: {
            NSLog(@"连网失败");
        }
            break;
        case TUser_Status_SigExpired: {
            NSLog(@"userSig过期");
        }
            break;
        default:
            break;
    }
}


- (void)onNewMessage:(NSArray*) msgs {
    
    [[TT_MessageManager manager] refreshUnReadCount];
    
    TIMMessage *msg = msgs.lastObject;
    NSString *content;
    NSLog(@"%@",msg);
    NSMutableArray *dic = @{}.mutableCopy;
    [dic setValue:@(10086) forKey:@"type"];
    
    for (int i = 0; i < msg.elemCount; ++i) {
        TIMElem *elem = [msg getElem:i];

        if ([elem isKindOfClass:[TIMTextElem class]]) {
            TIMTextElem *gt = (TIMTextElem *)elem;
            content = gt.text;
            content = [NSString stringWithFormat:@"您收到一条消息：“%@”，请进入消息列表查看",content];
        } else if ([elem isKindOfClass:[TIMImageElem class]]) {
            content = [NSString stringWithFormat:@"您收到一条图片消息，请进入消息列表查看"];
        } else if ([elem isKindOfClass:[TIMSoundElem class]]) {
            content = [NSString stringWithFormat:@"您收到一条语音消息，请进入消息列表查看"];
        } else if ([elem isKindOfClass:[TIMVideoElem class]]) {
            content = [NSString stringWithFormat:@"您收到一条视频消息，请进入消息列表查看"];
        } else {
            return;
        }
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

        [TTStatusBarUtilities showAndHideDuration:3.f];
        [TTStatusBarUtilities showWithView:[TTMessageView messageViewWithTitle:content backgroundColor:UIColorHex(0xff4242)] hideAfterSeconds:3.f];
    }
}




#pragma mark ----------- 封装api -----------
- (void)TTIM_InitSDK {
    [[TUIKit sharedInstance] setupWithAppId:1400408971 logLevel:V2TIM_LOG_ERROR];
    
}

- (int)TTIM_Login:(TIMLoginParam*)param succ:(TIMLoginSucc)succ fail:(TIMFail)fail {
    
    return [[TIMManager sharedInstance] login:param succ:succ fail:fail];
}

- (int)TTIM_GetUnreadMsgCount {
    
    //获取未读计数
    int unReadCount = 0;
    NSArray *convs = [[TIMManager sharedInstance] getConversationList];
    for (TIMConversation *conv in convs) {
        if([conv getType] == TIM_SYSTEM){
            continue;
        }
        unReadCount += [conv getUnReadMessageNum];
    }
    return unReadCount;
}

- (int)TTIM_LogOut:(TIMLoginSucc)succ fail:(TIMFail)fail {
    return [[TIMManager sharedInstance] logout:succ fail:fail];
}


- (void)TTIM_JoinGrop:(NSString *)groupId msg:(NSString*)msg succ:(TIMSucc)succ fail:(TIMFail)fail {
    [[TIMGroupManager sharedInstance] joinGroup:groupId msg:msg succ:succ fail:fail];
}


- (void)TTIM_GetGroupMenberList:(NSString*)groupId succ:(TIMGroupMemberSucc)succ fail:(TIMFail)fail {
    [[TIMGroupManager sharedInstance] getGroupMembers:groupId succ:succ fail:fail];
}


- (void)TTIM_QuitGroup:(NSString*)groupId succ:(TIMSucc)succ fail:(TIMFail)fail {
    [[TIMGroupManager sharedInstance] quitGroup:groupId succ:succ fail:fail];
}

- (void)TTIM_DeleteGroupConversation:(NSString*)groupId {
    
    [[TIMManager sharedInstance] deleteConversation:TIM_GROUP receiver:groupId];
}

- (void)TTIM_DeleteConversationAndMessages:(NSString*)groupId {
    
//    [[TIMManager sharedInstance] deleteConversationAndMessages:TIM_GROUP receiver:groupId];
    [[TIMManager sharedInstance] deleteConversation:TIM_GROUP receiver:groupId];

}

- (void)TTIM_GetSelfProfile:(TIMGetProfileSucc)succ fail:(TIMFail)fail {
    [[TIMFriendshipManager sharedInstance] getSelfProfile:succ fail:fail];
}

- (void)TTIM_GetUserProfile:(NSArray<NSString *> *)identifiers forceUpdate:(BOOL)forceUpdate succ:(TIMUserProfileArraySucc)succ fail:(TIMFail)fail {
    [[TIMFriendshipManager sharedInstance] getUsersProfile:identifiers forceUpdate:forceUpdate succ:succ fail:fail];
}

- (void)TTIM_SetSelfProfile:(NSDictionary *)dic succ:(TIMSucc)succ fail:(TIMFail)fail {
    /*
     TIMProfileTypeKey_Nick    NSString    昵称
     TIMProfileTypeKey_FaceUrl    NSString    头像
     TIMProfileTypeKey_AllowType    NSNumber    好友申请
     TIMProfileTypeKey_Gender    NSNumber    性别
     TIMProfileTypeKey_Birthday    NSNumber    生日
     TIMProfileTypeKey_Location    NSString    位置
     TIMProfileTypeKey_Language    NSNumber    语言
     TIMProfileTypeKey_Level    NSNumber    等级
     TIMProfileTypeKey_Role    NSNumber    角色
     TIMProfileTypeKey_SelfSignature    NSString    签名
     TIMProfileTypeKey_Custom_Prefix    NSString、NSData 或 NSNumber    自定义字段前缀
     */
    
    [[TIMFriendshipManager sharedInstance] modifySelfProfile:dic succ:succ fail:fail];
//    [[TIMFriendshipManager sharedInstance] modifySelfProfile:dic succ:succ fail:fail];
}

@end
